// TomboyRevisions.cs created with MonoDevelop
// User: devon at 7:52 P 11/10/2008
using System;
using System.IO;
using System.Xml;
using Mono.Unix;
using Gtk;


namespace Tomboy.TomboyRevisions
{	
	public class TomboyRevisionsAddin : NoteAddin
	{	
		//called when a note is created
		public override void Initialize ()
        {
			Logger.Log("Tomboy Revisions initialized.");
        }

	    public override void Shutdown ()
	    {
	    }

        public override void OnNoteOpened ()
        {
			Note.Saved += new NoteSavedHandler(OnNoteSaved);
        }
		
		public void OnNoteSaved(Note note) 
		{
			//Save the new revision
			RevisionManager.AddRevision(note, Manager);
		}
	}
	
	class RevisionManager
	{
		const string REVISION_PATH = "revisions";
		const string REVISION_EXTENSION = "rev";
		public static void AddRevision(Note note, NoteManager manager)
		{
			string revision_directory = Path.Combine(manager.NoteDirectoryPath, 
			                                         REVISION_PATH);
			
			string revision_filename = Path.GetFileName(note.FilePath) + 
										"." + REVISION_EXTENSION;
			
			string revision_file_path = Path.Combine(revision_directory, 
			                                         revision_filename);
			
			Logger.Log("Writing revision file: " + revision_file_path);
			
			//Create the revisions directory if it doesn't exist.
			if (!Directory.Exists(revision_directory)) {
				Logger.Log("Tomboy Revisions: Directory doesn't exist, creating");
				Directory.CreateDirectory(revision_directory);
			}
			
			XmlDocument revision_xml = new XmlDocument();
			try {
				revision_xml.Load(revision_file_path);
			}
			catch(System.IO.FileNotFoundException) {
				Logger.Log("Tomboy Revisions: Revision file doesn't exist.");
				XmlTextWriter xmlWriter = new XmlTextWriter(revision_file_path, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteStartElement("tomboy-revisions");
				xmlWriter.WriteEndElement();
				xmlWriter.Close();
                revision_xml.Load(revision_file_path);
			}
			WriteRevision(note, revision_xml);
		}
		
		private static void WriteRevision(Note note, XmlDocument doc) {
			Logger.Log("Writing note revision");
		}
	}
}
